
package com.epam.android.training.level1.activity;

import com.epam.android.training.level1.R;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.MotionEvent;

/**
 * Activity that controls view and behaviour of splash logo.
 * 
 * @author Anton Novikau
 */
public class SplashActivity extends Activity implements IntentActions {

  /**
   * System handeler that controls the lifetime of the startup splash.
   */
  private Handler splashHandler;

  private SharedPreferences preferences;

  /** Called when the activity is first created. */
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);
    preferences = PreferenceManager.getDefaultSharedPreferences(this);

    launchSplashThread();
  }

  private void launchSplashThread() {
    // load splash timeout from resources and convert the result to millis.
    final int splashTimeout = getResources().getInteger(R.integer.splash_timeout) * 1000;

    // instantiate splash handeler with anonimous handeler implementation to
    // control the lifetime of the splash.
    splashHandler = new Handler() {
      private boolean splashClosed;

      @Override
      public void handleMessage(Message msg) {

        // do not send intent after timeout expires if user tapped to the screen
        // first.
        if (!splashClosed) {
          // finish splash screen activity.
          finish();

          // start default activity
          String defaultPageAction = preferences.getString(SettingsActivity.DEFAULT_PAGE_KEY,
              ACTION_TESTS);
          Intent intent = new Intent(defaultPageAction);
          startActivity(intent);

          splashClosed = true;
        }
      };
    };

    // send notification to handeler to close splash logo and load default
    // activity right after timeout expires.
    splashHandler.sendEmptyMessageDelayed(0, splashTimeout);
  }

  /**
   * Called when a touch screen event was not handled by any of the views under
   * it. Sends notification to splash handeler to force splash logo activity
   * closing and load a default page.
   */
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
      return splashHandler.sendEmptyMessage(0);
    }

    return super.onTouchEvent(event);
  }
}
